<!--eslint-disable vue/no-unused-vars-->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table :data="cateAllList" :columns="columns" :selection-type="false"
      :expand-type="false" :show-index="true" index-text="#" border>
        <template slot="isok" slot-scope="scope">
            <i class="el-icon-success" v-if="!scope.row.cat_delete" style="color:green;"></i>
            <i class="el-icon-error" v-else style="color:red;"></i>
        </template>
        <template slot="tagname" slot-scope="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
            <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="caozuo" slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editType(scope.row.cat_id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteType(scope.row.cat_id)"></el-button>
        </template>
      </tree-table>
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <el-form label-width="100px" :model="addForm" ref="addFormRef" :rules="addFormRules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="级别选择">
          <el-cascader clearable change-on-select
            v-model="selectedKey"
            :options="type2CateList"
            :props="cascaderProps"
            @change="cascaderChange">
         </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddDia">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑的对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form label-width="100px" :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditDia">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
        //商品分类的所有数据
        cateAllList:[],
        querInfo: {
            type: 3,
            pagenum: 1,
            pagesize: 5
        },
        total:0,
        columns:[
            {
                label:"分类名称",
                prop:'cat_name'
            },
            {
                label:"是否有效",
                type:'template',//这一列使用作用域插槽渲染
                template:'isok'
            },
            {
                label:"级别",
                type:'template',
                template:'tagname'
            },
            {
                label:"操作",
                type:'template',
                template:'caozuo'
            }
        ],
        addDialogVisible:false,
        editDialogVisible:false,
        addForm:{
            cat_pid:0,
            cat_name:'',
            cat_level:0
        },
        addFormRules:{
            cat_name:[
                { required: true, message: '请输入分类名称', trigger: 'blur' },
                {
                    min: 3,
                    max: 10,
                    message: '长度在3~10个字符之间',
                    trigger: 'blur'
                }
            ]
        },
        editForm:{
        },
        editFormRules:{
            cat_name:[
                { required: true, message: '请输入分类名称', trigger: 'blur' },
                {
                    min: 3,
                    max: 10,
                    message: '长度在3~10个字符之间',
                    trigger: 'blur'
                }
            ]
        },
        type2CateList:[],
        cascaderProps:{ 
            value:'cat_id',
            label:'cat_name',
            children:'children'
             },
        selectedKey:[]  //选中的选项的id数组
    }
  },
  created() {
      this.getCateData()
  },
  methods: {
     async getCateData(){
        const {data:res} =await this.$http.get('categories',{params:this.querInfo})
        if(res.meta.status != 200) return this.$message.error('获取数据失败')
       // this.$message.success('获取数据成功')
        console.log(res.data)
        this.cateAllList = res.data.result;
        this.total = res.data.total;
      },
      handleSizeChange(val){
        this.querInfo.pagesize = val;
        this.getCateData()
      },
      handleCurrentChange(val){
        this.querInfo.pagenum = val;
        this.getCateData()
      },
      addDialog(){
          this.addDialogVisible = true;
          this.getCurrentCateList()
      },
      addDialogClose(){
          this.$refs.addFormRef.resetFields();
          this.selectedKey=[];
          this.addForm.cat_pid = 0;
          this.addForm.cat_level = 0;
      },
      editDialogClose(){
        this.$refs.editFormRef.resetFields();
      },
      async getCurrentCateList(){
          const {data:res} =await this.$http.get('categories',{params:{type:2}})
          if(res.meta.status != 200) return this.$message.error('获取数据失败')
          console.log(res.data)
          this.type2CateList = res.data;
      },
      cascaderChange(){
          console.log(this.selectedKey)
          //selectedKey数据长度为空表示为一级分类  cat_level = 0, 1-》二级 cat_level = 1, 2-》三级
          if(this.selectedKey.length > 0 ){
            this.addForm.cat_pid =this.selectedKey[this.selectedKey.length - 1]; //获取到最近的父级的id
            this.addForm.cat_level = this.selectedKey.length;
          }
          else{
            this.addForm.cat_pid = 0;
            this.addForm.cat_level = 0;
          }  
      },
      submitAddDia() {
          this.$refs.addFormRef.validate(async valid=>{
              if(!valid) return;
              const {data:res} =await this.$http.post('categories',this.addForm);
              //console.log(res.mata)
              this.$message.success('添加成功')
              this.addDialogVisible = false;
              this.getCateData()

          })
      },
      async editType(catid){
        const {data:res} = await this.$http.get(`categories/${catid}`)
          if(res.meta.status != 200) this.$message.error('获取失败')
          else{
              console.log(res);
              this.editForm = res.data;
          }
          this.editDialogVisible = true;
      },
      deleteType(catid){
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async () => {
            const {data:res} = await this.$http.delete(`categories/${catid}`);
            if(res.meta.status != 200) return this.$message.error('删除失败')
            this.$message.success('删除成功');
            this.getCateData();   
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
      },
      submitEditDia(){
        this.$refs.editFormRef.validate(async valid=>{
              if(!valid) return;
              const {data:res} = await this.$http.put(`categories/${this.editForm.cat_id}`,{
                  cat_name:this.editForm.cat_name
              });
              if(res.meta.status !=200) return this.$message.error('编辑失败');
              this.$message.success('编辑成功');
              this.getCateData();
              this.editDialogVisible = false;
          })
      }
  },
  components: {

  }
}
</script>

<style lang='less' scoped>

.el-button{
    margin-bottom: 10px;
}
.el-cascader{
    width: 100%;
    
}

</style>
